package com.swgk.core.recyclerview.adapter;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.fragment.app.FragmentTransaction;

import android.util.Log;
import android.view.ViewGroup;

import java.util.ArrayList;

/**
 * Description:
 * Author zhengkewen
 * Time 2017/8/2 14:44
 */
public class FragPagerAdapter extends FragmentPagerAdapter {
    private ArrayList<Fragment> fragments;
    private FragmentManager fm;

    public FragPagerAdapter(FragmentManager fm) {
        super(fm);
        this.fm = fm;
    }

    public FragPagerAdapter(FragmentManager fm,
                            ArrayList<Fragment> fragments) {
        super(fm);
        this.fm = fm;
        this.fragments = fragments;
    }

    @Override
    public int getCount() {
        return fragments.size();
    }

    @Override
    public Fragment getItem(int position) {
        return fragments.get(position);
    }

    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }

    public void setFragments(ArrayList<Fragment> fragments) {
        if (this.fragments != null) {
            FragmentTransaction ft = fm.beginTransaction();
            for (Fragment f : this.fragments) {
                ft.remove(f);
            }
            ft.commit();
            ft = null;
            fm.executePendingTransactions();
        }
        this.fragments = fragments;
        notifyDataSetChanged();
    }

    @Override
    public Object instantiateItem(ViewGroup container, final int position) {
        Object obj = super.instantiateItem(container, position);
        return obj;
    }

    @Override
    public long getItemId(int position) {
        //super.getItemId(position);
        //重写getItemId方法，把super方法去除换成新对象的hashcode  避免fragment bundle取值永远从缓存取，取不到最新的
        return fragments.get(position).hashCode();
    }
}
